# import frappe
# from frappe import _

# import frappe
# import json
# from frappe import _

# @frappe.whitelist(allow_guest=False)
# def get_item_by_items():
#     '''
#     批量查询物料主数据（所有 item_code 均存在）
#     '''
#     try:
#         data = frappe.local.form_dict.data
#         if isinstance(data, str):
#             data = json.loads(data)

#         # 提取 item_code 列表
#         item_codes = [entry.get("物料编号") for entry in data if entry.get("物料编号")]

#         if not item_codes:
#             return {
#                 "status": "error",
#                 "message": "未提供有效的 item_code 列表"
#             }

#         # 批量查询 item 数据
#         items = frappe.get_all(
#             "Item",
#             filters={"item_code": ["in", item_codes]},
#             fields=[
#                 "item_code as 内部镀种号",
#                 "custom_客户镀种 as 客户镀种",
#                 "custom_客户料号 as 客户料号",
#                 "custom_规格 as 规格",
#                 "custom_终客户 as 终客户"
#             ]
#         )

#         return {
#             "status": "success",
#             "data": items
#         }

#     except Exception as e:
#         frappe.log_error(frappe.get_traceback(), "Batch Get Item Error")
#         return {
#             "status": "error",
#             "message": f"服务器异常: {str(e)}"
#         }

import frappe
import json
from frappe import _

@frappe.whitelist(allow_guest=False)
def get_items_by_customer_info():
    '''
    根据客户信息（客户镀种、客户料号、规格、终客户）反查物料编号（AND 关系）
    '''
    try:
        data = frappe.local.form_dict.data
        if isinstance(data, str):
            data = json.loads(data)

        # 验证输入数据
        if not isinstance(data, list) or not data:
            return {
                "status": "error",
                "message": "请求数据无效或为空"
            }

        results = []

        for entry in data:
            # 检查必须字段是否都提供了
            if not all([
                entry.get("客户镀种"),
                entry.get("客户料号"),
                entry.get("规格")
                # entry.get("终客户")
            ]):
                continue  # 跳过字段不完整的记录

            filters = {
                "custom_客户镀种": entry["客户镀种"],
                "custom_客户料号": entry["客户料号"],
                "custom_规格": entry["规格"]
                # "custom_终客户": entry["终客户"]
            }

            items = frappe.get_all(
                "Item",
                filters=filters,
                fields=[
                    "item_code as 物料编号",
                    "custom_客户镀种 as 客户镀种",
                    "custom_客户料号 as 客户料号",
                    "custom_规格 as 规格",
                    "custom_终客户 as 终客户"
                ]
            )

            if items:
                results.extend(items)

        if not results:
            return {
                "status": "error",
                "message": "未找到匹配的物料数据"
            }

        return {
            "status": "success",
            "data": results
        }

    except Exception as e:
        frappe.log_error(frappe.get_traceback(), "Reverse Lookup Item Error")
        return {
            "status": "error",
            "message": f"服务器异常: {str(e)}"
        }
